package com.cr.backbone.ajax.upload;

import java.io.File;
import java.util.ArrayList;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.cr.backbone.action.AppBaseActionSupport;
import com.cr.backbone.model.SysFile;
import com.cr.backbone.service.business.sysfile.SysFileService;
import com.cr.backbone.util.UtilsConfig;
import com.cr.backbone.util.UtilsDateTime;
import com.cr.backbone.util.UtilsFile;
import com.readnote.user.model.User;
import com.readnote.user.model.UserInfo;
import com.readnote.user.service.UserInfoService;
import com.sun.org.apache.commons.beanutils.BeanUtils;

/**
 * 
 * 文件上传Action
 * @author huxh
 * @date 2012-6-11
 */
public class AjaxUploadFileAction extends AppBaseActionSupport{
	
	private ArrayList<SysFile> sysFiles=new ArrayList<SysFile>();//上传成功FileIds

	
	private UserInfoService userInfoService;
	private SysFileService sysFileService;
	private Long[] abss;
	private User user;
	
//	private String error="";
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1179031234511250745L;

	
	
	public String input() {
		return INPUT;
	}

	public String saveSysFile() {
		
		try {
			//执行文件上传
			//1 保存文件到服务器
//			File uploadFile = saveFileToServer(upload,uploadFileName);
			File uploadFile = UtilsFile.saveFileToServer(upload,uploadFileName);
			
			
			String fileTitle=uploadFileName;
			String fileType=uploadContentType;
			User createUser=getLoginInfo().getUser();//当前登录者
			String createUserName="匿名用户";
			if(createUser !=null && !createUser.isNullRow() ){
				UserInfo uInfo = userInfoService.getUserInfoByUser(createUser);
				createUserName = uInfo.getRealName();
			}
			String createIp=ServletActionContext.getRequest().getLocalAddr();//请求者本地IP
			String remoteIp=ServletActionContext.getRequest().getRemoteAddr();//请求远程IP
			
			//2 将文件保存到服务器并保存SysFile
//			SysFile sf1=saveSysFile(uploadFile, fileTitle ,fileType, createUserName, createUser, createIp);
			SysFile sf=sysFileService.saveSysFile(uploadFile, fileTitle ,fileType, createUserName, createUser, createIp);
			sysFiles.add( sf );
			
//			SysFile result= new SysFile();
//			SysFile src=sf;
//			SysFile dest=result;
//			BeanUtils.copyProperties(dest, src);
			//
//			sysFiles.add( dest );
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			String error=e.getMessage();
			addActionError("上传文件异常："+error);
			return INPUT;
		}
		
		
		return SUCCESS;
	}
	
	/**
	 * 
	 * 
	 * @param file
	 * @author huxh
	 * @date 2012-6-14
	 */
	@Deprecated
	private SysFile saveSysFile(File file,String fileTitle,String fileType,String createUserName,User createUser,String createIp) {
		SysFile sysFile = null;
		// 1 验证源文件是否存在
		if(file == null){
			return sysFile;
		}
		
		// 2 保存文件记录
		sysFile=new SysFile();
		
		sysFile.setCreateDate(UtilsDateTime.getCurrentDate());
		sysFile.setCreateUser(createUser);
		sysFile.setCreateUserName(createUserName);
		sysFile.setCreateClientIp(createIp);
		
		
		String fileRealPath=file.getPath();
		String fileName=file.getName();
		String FILE_PATH_ROOT="uploadFile";
		int beginIndex = fileRealPath.indexOf(FILE_PATH_ROOT);
		String filePath=fileRealPath.substring(beginIndex);
		
		
		sysFile.setFileType(fileType);
		sysFile.setFileTitle(fileTitle);
		sysFile.setFileName(fileName);
		sysFile.setFilePath(filePath);
		sysFile.setFileRealPath(fileRealPath);
		sysFile.setFileSize(UtilsFile.getFileSizeKMG(file.length()));
		sysFile.setFileSizeUnit(UtilsFile.getFileSizeKFormat(file.length()));
		
		
		sysFile.setFileSubfix(UtilsFile.getFileExt(fileName));
		
		
		return sysFile;
	}

	private File upload;
	private String uploadFileName;
	private String uploadContentType;
	private FileUtils fileUtils;//文件读写处理工具类
	
	/**
	 * 文件保存到服务器
	 * 
	 * @param upload
	 * @param uploadFileName
	 * @return
	 * @throws Exception
	 * @author huxh
	 * @date 2012-6-15
	 * 
	 * 转移到UtilsFile
	 */
	@Deprecated
	public File saveFileToServer(File upload,String uploadFileName) throws Exception{
		try {
			if(upload ==null || uploadFileName == null || "".equals(uploadFileName))
				return null;
			File srcFile=upload;
			
			
			// 1  保存文件
			// 1.1 保存文件目录
			String realPath  = ServletActionContext.getServletContext().getRealPath(UtilsConfig.FILE_PATH_UPLOAD_ROOT_FOLDER);//root
			// root
			StringBuffer path=new StringBuffer(realPath);
			
			int beginIndex=uploadFileName.indexOf(".");
			int endIndex=uploadFileName.length();
			String FileSuffix = uploadFileName.substring((beginIndex+1), endIndex);
			// file suffix
			path.append("/");
			path.append(FileSuffix);
			path.append("/");
			// date
			path.append(UtilsDateTime.getCurrentDateString());
			
			//1.2 保存文件名称
			StringBuffer newFileName = new StringBuffer(); 
			//newFileName.append(UtilsDateTime.getCurrentDateTimeString("yyyy-MM-dd_hh:mm:ss"));
			newFileName.append(UtilsDateTime.getCurrentDateTimeString("yyyy-MM-dd_hhmmss"));
			newFileName.append("_____");
			newFileName.append(FileSuffix);
			newFileName.append("_____");
			newFileName.append(System.currentTimeMillis());
			newFileName.append(".");
			newFileName.append(FileSuffix);
			
			
			// dest file 
//			File destFile=new File(new File(realPath),uploadFileName);
//			if(!destFile.getParentFile().exists()){
//				destFile.getParentFile().mkdirs();
//			}
//			
//			fileUtils.copyFile(srcFile, destFile);

			// new dest file 
			String newPath=UtilsFile.getPath(path.toString());//windos linux 文件夹目录调整
			System.out.println(newPath);
			File newDestFile=new File(new File( newPath ),newFileName.toString());
			if(!newDestFile.getParentFile().exists()){
				newDestFile.getParentFile().mkdirs();
			}
			
			// 文件copy
			UtilsFile.copyFile(srcFile, newDestFile);
			System.out.println(newDestFile.getPath());
			return newDestFile;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
		
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public FileUtils getFileUtils() {
		return fileUtils;
	}

	public void setFileUtils(FileUtils fileUtils) {
		this.fileUtils = fileUtils;
	}

	public ArrayList<SysFile> getSysFiles() {
		return sysFiles;
	}

	public void setSysFiles(ArrayList<SysFile> sysFiles) {
		this.sysFiles = sysFiles;
	}



	public void setUserInfoService(UserInfoService userInfoService) {
		this.userInfoService = userInfoService;
	}


	public void setSysFileService(SysFileService sysFileService) {
		this.sysFileService = sysFileService;
	}


	
	
	
	
	
	
	
	
	
	
	
	
	
	
//	
//	
//	
//	
//	public String uploadFile() throws Exception {
//		  String extName = "";//扩展名
//		  String newFileName= "";//新文件名
//		 
//		  String nowTime = new SimpleDateFormat("yyyymmddHHmmss").format(new Date());//当前时间
//		 
//		  String savePath = ServletActionContext.getRequest().getRealPath("");
//		 
//		  savePath = savePath +"/uploads/";
//		  HttpServletResponse response = ServletActionContext.getResponse();
//		  response.setCharacterEncoding("utf-8");
//		 
//		  //获取扩展名
//		  if(uploadFileName.lastIndexOf(".")>=0){
//		   extName = uploadFileName.substring(uploadFileName.lastIndexOf("."));
//		  }
//		  newFileName = nowTime+extName;
//		 
////		  uploadify.renameTo(new File(savePath+newFileName));
//		 
//		  sysFileIds=new Long[1];
//		  sysFileIds[0]=1l;
//		  response.getWriter().print(uploadFileName+"上传成功！<input type='hidden' name='sysFileIds' value='"+sysFileIds+"' />");
//		  return "ok"; //这里输入什么字串都行。注意不能是nul，否则进度条不走完
//
//
//	}




	
}
